package com.groupfive.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.groupfive.exception.CustomException;
import com.groupfive.mapper.DeptMapper;
import com.groupfive.pojo.Dept;
import com.groupfive.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class DeptServiceImpl implements DeptService {

    @Autowired
    private DeptMapper deptMapper;

    /**
     * 查询所有
     */
    @Override
    public List<Dept> selectAll(Dept dept) {
        return deptMapper.selectAll(dept);
    }

    /**
     * 根据id查询
     */
    @Override
    public Dept selectById(Long id) {
        return deptMapper.selectById(id);
    }

    /**
     * 分页查询
     */
    @Override
    public PageInfo<Dept> selectPage(Dept dept, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum,pageSize);
        List<Dept> list = deptMapper.selectAll(dept);
        return PageInfo.of(list);
    }

    /**
     * 新增
     */
    @Override
    public int add(Dept dept) {
        String name = dept.getName();
        Dept dbDept = deptMapper.selectByName(name);
        if (dbDept != null){
            throw new CustomException("500","部门已存在");
        }
        return deptMapper.insert(dept);
    }

    /**
     * 更新
     */
    @Override
    public int update(Dept dept) {
        String name = dept.getName();
        Dept dbDept = deptMapper.selectByName(name);
        if (dbDept != null){
            throw new CustomException("500","部门已存在");
        }
        return deptMapper.update(dept);
    }

    /**
     * 删除
     */
    @Override
    public int deleteById(Long id) {
        return deptMapper.deleteById(id);
    }

    @Override
    public void deleteBatch(List<Long> ids) {
        for (Long id : ids) {
            this.deleteById(id);
        }
    }
}
